package models

import (
	"gintest/database"
	"time"
)
//表结构
type AuthUser struct {
	Id        int    `json:"id" gorm:"column:id;primary_key" form:"id"`
	UserName string `json:"username" gorm:"column:username" form:"username"`
	PassWord  string `json:"password" gorm:"column:password" form:"password"`
	CreateAt time.Time  `json:"create_at" gorm:"column:create_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"create_at"`
	UpdateAt time.Time  `json:"update_at" gorm:"column:update_at;type:datetime" time_format:"2006-01-02 15:04:05" form:"update_at"`
	Status uint8 `json:"status" gorm:"status" form:"status"`
}
func (AuthUser) TableName() string {
	return "auth_users"
}
//得到记录
func GetAuthUserForUsername(username string) (authusers AuthUser) {
	database.SqlDB.Model(AuthUser{}).Where("username=?",username).First(&authusers)
	return authusers
}
//得到记录列表
func GetAuthUserList(page uint64,pagesize uint64,keyword string) (data []AuthUser,total uint64) {
	var offset=(page-1)*pagesize
	db:=database.SqlDB.Model(AuthUser{})
	if len(keyword)!=0{
		db=db.Where("concat(id,username) like ?", "%"+keyword+"%")
	}
	db.Offset(offset).Limit(pagesize).Order("id desc").Find(&data)
	db.Model(AuthUser{}).Count(&total)
	return data,total
}
func AddAuthUser(data *AuthUser) error{
	if data.UpdateAt.IsZero(){
		data.UpdateAt=time.Now()
	}
	if data.CreateAt.IsZero(){
		data.CreateAt=time.Now()
	}
	return database.SqlDB.Model(AuthUser{}).Create(data).Error
}
func DelAuthUserByIds(ids []int) error{
	return database.SqlDB.Model(AuthUser{}).Where("id in (?)",ids).Delete(AuthUser{}).Error
}
func GetAuthUserById(id int) (data AuthUser){
	database.SqlDB.Model(AuthUser{}).Where("id=?",id).First(&data);
	return data
}
func EditAuthUserById(id int,data interface{}) error{
	//update_at不存在，填充当前时间
	if _, has := data.(map[string]interface{})["update_at"]; !has {
		data.(map[string]interface{})["update_at"]=time.Now()
	}
	//database.SqlDB.Model(AuthUser{}).Where("id = ?", data.Id).Updates(data)
	return database.SqlDB.Model(AuthUser{}).Where("id=?",id).Updates(data).Error
}